<template>
  <!-- 审核流程配置 -->
  <el-timeline>
    <el-timeline-item
      v-for="(item, index) in configList"
      :key="index"
      center
      :timestamp="item.time"
      placement="top"
      size="large"
      :type="item.type"
      :color="item.color"
      :icon="item.icon"
    >
      <el-card v-if="item.node !== 'middle'">
        <div class="startNode" v-if="item.node == 'start'">
          <div class="round">{{ item.shortName }}</div>
          <p>{{ item.username }}: 发起{{ this.auditTitle }}审批</p>
        </div>
        <div class="endNode" v-if="item.node == 'end'">
          <p>
            审批{{
              item.totalStatus == 0
                ? "审核中"
                : item.totalStatus == 1
                ? "通过"
                : "未通过"
            }}
          </p>
          <p>此流程{{ item.totalStatus !== 0 ? "已结束" : "进行中" }}</p>
        </div>
      </el-card>
      <template v-if="item.node == 'middle' && item.auditType != 1">
        <el-card
          v-for="info in item.list"
          :key="info.id"
          v-show="item.node == 'middle'"
          :style="{ opacity: info.preStatus == 0 ? 0.5 : 1 }"
        >
          <div class="node" v-if="isReloadData">
            <div class="topInfo">
              <div class="round" v-if="info.shortName">
                {{ info.shortName }}
              </div>
              <div class="info">
                <p>{{ info.auditTime }}</p>
                <p>
                  {{ info.auditName }}:
                  {{
                    info.status == 0
                      ? "待审核"
                      : info.status == 1
                      ? "通过"
                      : "未通过"
                  }}
                </p>
              </div>
            </div>
            <p class="remark" v-if="info.reason">审批意见：{{ info.reason }}</p>
            <div class="successButton icon" v-if="info.status == 1">
              <el-icon><el-icon-check /></el-icon>
            </div>
            <div class="closeButton icon" v-if="info.status == 2">
              <el-icon><el-icon-close /></el-icon>
            </div>
            <div
              class="handleButton"
              v-if="
                info.status == 0 &&
                info.preStatus == 1 &&
                info.totalStatus == 0 &&
                info.auditId == userId
              "
            >
              <el-button type="primary" size="small" @click="handleAudit(info)"
                >审 批</el-button
              >
            </div>
            <!-- <div
              class="handleButton"
              v-if="
                info.status != 0 &&
                info.totalStatus != 0 &&
                info.auditId == userId
              "
            >
              <el-button type="warning" size="small" @click="reverseAudit(info)"
                >反审批</el-button
              >
            </div> -->
          </div>
        </el-card>
      </template>
      <template v-else>
        <el-card
          v-show="item.node == 'middle'"
          :style="{ opacity: item.preStatus == 0 && index > 1 ? 0.5 : 1 }"
        >
          <div class="node" v-if="isReloadData">
            <div class="topInfo">
              <div class="round" v-if="item.shortName">
                {{ item.shortName }}
              </div>
              <div class="info">
                <p>{{ item.auditTime }}</p>
                <p>
                  {{ item.auditName }}:
                  {{
                    item.status == 0
                      ? "待审核"
                      : item.status == 1
                      ? "通过"
                      : "未通过"
                  }}
                </p>
              </div>
            </div>
            <p class="remark" v-if="item.reason">审批意见：{{ item.reason }}</p>
            <div class="successButton icon" v-if="item.status == 1">
              <el-icon><el-icon-check /></el-icon>
            </div>
            <div class="closeButton icon" v-if="item.status == 2">
              <el-icon><el-icon-close /></el-icon>
            </div>
            <div
              class="handleButton"
              v-if="
                item.status == 0 &&
                item.totalStatus == 0 &&
                item.preStatus == 1 &&
                item.auditId == userId
              "
            >
              <el-button type="primary" size="small" @click="handleAudit(item)"
                >审 批</el-button
              >
            </div>
            <!-- <div
              class="handleButton"
              v-if="
                item.status != 0 &&
                item.totalStatus != 0 &&
                item.auditId == userId
              "
            >
              <el-button type="warning" size="small" @click="reverseAudit(item)"
                >反审批</el-button
              >
            </div> -->
          </div>
        </el-card>
      </template>
    </el-timeline-item>
  </el-timeline>
  <check-dialog ref="checkDialog" @update="relodPart"></check-dialog>
</template>
<script>
import checkDialog from '@/components/checkDialog'
export default {
  name: 'checkProcess',
  emits: ['updatePage'],
  data () {
    return {
      userId: '',
      configList: [],
      loading: false,
      isReloadData: true,//局部刷新标识
      auditTitle: ''
    }
  },
  components: {
    checkDialog
  },
  props: {
    id: {
      require: true,
      type: String
    },
    type: {
      require: true,
      type: Number
    },
  },
  mounted () {
    let userInfo = this.$TOOL.data.get('USER_INFO')
    this.userId = userInfo.userId
    // 获取审批流程配置
    this.getCheckConfigDetail()
    // 获取流程类型名称
    this.getDictsortDetailOne()
  },
  methods: {
    async getDictsortDetailOne () {
      let param = {
        code: 'streamCode',
        value: this.type
      }
      let res = await this.$API.common.detail.getDictsortDetailOne.get(param)
      this.auditTitle = res.data.name
    },
    // 获取审批流程配置
    async getCheckConfigDetail () {
      let param = {
        id: this.id,
        type: this.type
      }
      let res = await this.$API.common.detail.getCheckConfigDetail.get(param)
      if (res.code == 200 && res.data.length > 0) {
        let list = this.classify(res.data)
        console.log(list)
        let startNode = {}
        let node = {}
        let endNode = {}
        let nodeList = []//会签 / 或签
        let checkInfo = {}
        let auditType = 0
        let itemNodeList = []//依次签
        list.forEach(l_item => {
          l_item.data.forEach(item => {
            startNode = {
              node: 'start',
              time: item.contractCreateTime,
              username: item.applicantName,
              shortName: item.applicantName && item.applicantName.substr(-1),
              type: 'primary',//primary / success / warning / danger / info
              icon: '',
            }
            node = {
              node: 'middle',
              time: item.auditType == 1 ? '依次顺序审核' : (item.auditType == 2 ? '会签（可同时审批，每个人必须审批通过）' : '或签(有一人审批通过即可)'),
              auditTime: item.auditTime,
              shortName: item.auditName && item.auditName.substr(-1),
              id: item.id,
              auditId: item.auditId,
              auditName: item.auditName,//审批人
              departmentName: item.departmentName,
              positionName: item.positionName,
              status: item.status,//审核分组状态 0，待审核，1审核通过，2审核不通过
              auditType: item.auditType,//审核类型：1、依次顺序审核，2、会签（可同时审批，每个人必须审批通过），3、或签(有一人审批通过即可)
              streamType: item.streamType,
              correlationId: item.correlationId,
              reason: item.reason,
              totalStatus: item.totalStatus,//审核分组总状态0，待审核，1审核通过，2审核不通过
              preStatus: item.preStatus,//依次顺序审核时 上一级是否已审核
              type: item.totalStatus == 0 ? 'warning' : (item.totalStatus == 1 ? 'success' : 'danger'),
              icon: item.totalStatus == 0 ? null : (item.totalStatus == 1 ? 'el-icon-check' : 'el-icon-close')
            }
            endNode = {
              node: 'end',
              // time: item.auditTime,
              totalStatus: item.totalStatus,
              type: item.totalStatus == 0 ? 'warning' : (item.totalStatus == 1 ? 'success' : 'danger'),
              icon: item.totalStatus == 0 ? null : (item.totalStatus == 1 ? 'el-icon-check' : 'el-icon-close')
            }

            if (item.auditType == 1) {
              // auditType = item.auditType
              node.type = item.status == 0 ? 'warning' : (item.status == 1 ? 'success' : 'danger')
              node.icon = item.status == 0 ? null : (item.status == 1 ? 'el-icon-check' : 'el-icon-close')
              this.configList.push(node)
            } else if (item.auditType == 2) {
              checkInfo = {
                node: 'middle',
                time: item.auditType == 1 ? '依次顺序审核' : (item.auditType == 2 ? '会签（可同时审批，每个人必须审批通过）' : '或签(有一人审批通过即可)'),
                auditType: item.auditType,
                type: item.totalStatus == 0 ? 'warning' : (item.totalStatus == 1 ? 'success' : 'danger'),
                icon: item.totalStatus == 0 ? null : (item.totalStatus == 1 ? 'el-icon-check' : 'el-icon-close')
              }
              nodeList.push(node)
              // auditType = item.auditType
            } else if (item.auditType == 3) {
              checkInfo = {
                node: 'middle',
                time: item.auditType == 1 ? '依次顺序审核' : (item.auditType == 2 ? '会签（可同时审批，每个人必须审批通过）' : '或签(有一人审批通过即可)'),
                auditType: item.auditType,
                type: item.totalStatus == 0 ? 'warning' : (item.totalStatus == 1 ? 'success' : 'danger'),
                icon: item.totalStatus == 0 ? null : (item.totalStatus == 1 ? 'el-icon-check' : 'el-icon-close')
              }
              itemNodeList.push(node)
            }
          })

          if (l_item.auditType == 1) {
            auditType = l_item.auditType
            console.log(this.configList)
            // this.configList.push(node)
          } else if (l_item.auditType == 2) {
            checkInfo.list = nodeList
            this.configList.push(checkInfo)
            auditType = l_item.auditType
          } else if (l_item.auditType == 3) {
            checkInfo.list = itemNodeList
            this.configList.push(checkInfo)
          }

        })

        this.configList.splice(0, 0, startNode)
        // if (auditType == 1) {
        //   // this.configList.push(itemNodeList)
        // } else if (auditType == 2 || auditType == 3) {
        //   // checkInfo.list = nodeList
        //   // this.configList.push(checkInfo)
        // }
        this.configList.push(endNode)

      }
      console.log('this.configList')
      console.log(this.configList)
    },

    // 审批
    handleAudit (item) {
      this.$nextTick(() => {
        this.$refs.checkDialog.open(item)
      })

    },
    // 反审批
    reverseAudit (data) {
      console.log(data)
      let param = {
        correlationId: data.correlationId,
        streamType: data.streamType,
      }
      this.$confirm('此操作将取消之前的审批, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await this.$API.workflow.handleReverseAudit.post(param)
        console.log(res)
        this.relodPart()
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })


    },

    relodPart () {
      this.configList = []
      this.getCheckConfigDetail()
      this.isReloadData = false
      this.$nextTick(() => {
        this.isReloadData = true
      })
      this.$emit('updatePage')
    },

    classify (arr) {
      let map = {}
      let myArr = []
      for (let i = 0; i < arr.length; i++) {
        if (!map[arr[i].auditOnly]) {
          myArr.push({
            auditOnly: arr[i].auditOnly,
            auditType: arr[i].auditType,
            data: [arr[i]]
          })
          map[arr[i].auditOnly] = arr[i]
        } else {
          for (let j = 0; j < myArr.length; j++) {
            if (arr[i].auditOnly === myArr[j].auditOnly) {
              myArr[j].data.push(arr[i])
              break
            }
          }
        }
      }
      return myArr
    }
  }
}
</script>
<style lang="scss" scoped>
.el-card {
  width: 20%;
  margin-right: 20px;
  margin-bottom: 20px;
  .startNode {
    display: flex;
    align-items: center;
  }
  .node {
    position: relative;
    .icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 30px;
      height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      font-size: 20px;
      font-weight: 600;
    }
    .successButton {
      background: #67c23a;
    }
    .closeButton {
      background: #f56c6c;
    }
    .topInfo {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
    }
    .remark {
      // margin-left: 45px;
    }
    .handleButton {
      float: right;
      margin: 15px 0;
    }
  }

  .endNode {
    p:first-child {
      // font-size: 16px;
    }
    p:last-child {
      // font-size: 14px;
      color: #ccc;
    }
  }

  .round {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    text-align: center;
    line-height: 40px;
    margin-right: 10px;
    background-color: #409eff;
    color: #fff;
  }
  .info {
    p:first-child {
      line-height: 1.2em;
      font-size: 12px;
      color: #909399;
    }
    p:last-child {
      // font-size: 14px;
    }
  }
}

:deep(.el-timeline-item__content) {
  display: flex;
  flex-wrap: wrap;
}

.waitCheck {
  opacity: 0.5;
}
</style>